﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using System.Collections;
using Newtonsoft.Json;
using System.Configuration;
using System.IO;

namespace SendIndustrialNetwork
{
    public class JxReportAndStatusService
    {
        private static string saveFilePath = ConfigurationManager.AppSettings["saveFilePath"].ToString();
        public void Excute()
        {
            var dirs = new DirectoryInfo(saveFilePath);
            foreach (FileInfo fi in dirs.GetFiles())
            {
                if (fi.Extension.Replace(".", "").ToLower() != "json")
                    continue;
                var jsonStr = File.ReadAllText(fi.FullName);
                var msg = string.Empty;
                try
                {
                    //工单报工接口
                    if (fi.FullName.Contains("RW"))
                    {
                        msg = orderReport(jsonStr);
                    }
                    //工序状态反馈接口
                    if (fi.FullName.Contains("ZT"))
                    {
                        msg = orderStatus(jsonStr);
                    }
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
                finally
                {
                    LYIndustryFileExchangeHelper.MoveBackFile(fi, "");
                    LogHelp.WriteLog("文件[" + fi.FullName + "]处理结果：" + msg);
                }
            }
        }

        #region "工序状态反馈接口"
        /// <summary>
        /// 3.2	工序状态反馈接口
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        private string orderStatus(string jsonStr)
        {
            string msg = string.Empty;
            SpecStatus specStatus = JsonConvert.DeserializeObject<SpecStatus>(jsonStr);
            LogHelp.WriteLog("MES接收FMS工序状态反馈接口结果_开始处理JSON:" + jsonStr);
            try
            {
                DataTable dispatchDt = OracleHelper.Query(string.Format(@"select csd.* from containerstepdispatch csd where csd.containerstepdispatchid='{0}' and isuse=0", specStatus.ContainerStepDispatchID)).Tables[0];
                if (dispatchDt.Rows.Count == 0)
                {
                    msg = "MES中未找到此任务,对应字段：containerstepdispatchid" + specStatus.ContainerStepDispatchID;
                    return msg;
                }
                var updateSQL = @" UPDATE apsplandetail SET state={0} WHERE apsplandetailid =(SELECT DISTINCT a.APSPLANDETAILID FROM containerstepdispatch csd 
                           LEFT JOIN APSPLANDETAIL a ON a.CONTAINERID =csd.CONTAINERID AND a.WORKFLOWSTEPID =csd.WORKFLOWSTEPID 
                           WHERE csd.ISUSE =0 AND csd.CONTAINERSTEPDISPATCHID ='{1}')";
                var result = OracleHelper.ExecuteSql(string.Format(updateSQL, specStatus.State, specStatus.ContainerStepDispatchID)) > 0;
                msg = result ? "MES工序任务状态更新成功" : "MES工序任务状态更新失败";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }
        #endregion

        #region "工单报工接口"
        /// <summary>
        /// 3.3	工单报工接口
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        private string orderReport(string jsonStr)
        {
            string msg = string.Empty;
            OrderReport orderReport = JsonConvert.DeserializeObject<OrderReport>(jsonStr);
            LogHelp.WriteLog("MES接收FMS工单报工接口结果_开始处理JSON:" + jsonStr);
            try
            {
                DataTable dispatchDt = OracleHelper.Query(string.Format(@"select csd.* from containerstepdispatch csd where csd.containerstepdispatchid='{0}' and isuse=0", orderReport.DispatchID)).Tables[0];

                if (dispatchDt.Rows.Count == 0)
                {
                    msg = "MES中未找到此任务,对应字段：DispatchID" + orderReport.DispatchID;
                    return msg;
                }

                var resourceid = OracleHelper.GetSingle("select r.resourceid from resourcedef r where r.resourcename ='" + orderReport.ReportResName + "'");
                if (resourceid == null)
                {
                    msg = "MES中未找到此设备,对应字段：ReportResName:" + orderReport.ReportResName;
                    return msg;
                }

                var reportEmpDt = OracleHelper.Query(string.Format(@"select sv.workcenterid,te.teamid,e.employeeid from employee e
                        left join sessionvalues sv on sv.sessionvaluesid=e.sessionvaluesid
                        left join teamemployee te on te.employeeid=e.employeeid
                        where e.employeename='{0}'", orderReport.ReportEmpName)).Tables[0];
                if (reportEmpDt.Rows.Count == 0)
                {
                    msg = "MES中未找到此人员,对应字段：ReportEmpName:" + orderReport.ReportEmpName;
                    return msg;
                }

                var checkerid = OracleHelper.GetSingle("select e.employeeid from employee e where e.employeename ='" + orderReport.CheckEmpName + "'");

                if (OracleHelper.Query(string.Format(@"select * from containerstepworkreport where containerstepdispatchid='{0}' and isuse=0 ", orderReport.DispatchID)).Tables[0].Rows.Count > 0)
                {
                    msg = "此任务MES中已有报工" + orderReport.DispatchID;
                    return msg;
                }

                if (orderReport.CheckItems.Count == 0)
                {
                    msg = "此任务的检测项内容为空";
                    return msg;
                }

                var para = new Dictionary<string, string>();
                var reportID = Guid.NewGuid().ToString();
                para.Add("DispatchID", orderReport.DispatchID);
                para.Add("CheckType", "2");
                para.Add("ContainerID", dispatchDt.Rows[0]["ContainerID"].ToString());
                para.Add("WorkflowStepID", dispatchDt.Rows[0]["WorkflowStepID"].ToString());
                para.Add("StepInfoID", dispatchDt.Rows[0]["StepInfoID"].ToString());
                para.Add("CreateDate", orderReport.ReportDate);
                para.Add("FactoryID", dispatchDt.Rows[0]["FactoryID"].ToString());
                para.Add("Isuse", "0");
                para.Add("Qty", orderReport.LossQty + orderReport.PassQty);
                para.Add("ResourceID", resourceid.ToString());
                para.Add("TeamID", reportEmpDt.Rows[0]["TeamID"].ToString());
                para.Add("WorkcenterID", reportEmpDt.Rows[0]["WorkcenterID"].ToString());
                para.Add("WorkerID", reportEmpDt.Rows[0]["employeeid"].ToString());
                para.Add("Lossqty", orderReport.LossQty);//报废数量
                para.Add("PassQty", orderReport.PassQty);//合格数量
                para.Add("ContainerStepWorkReportID", reportID);

                var sqlList = new ArrayList();
                var faDispatcID = OracleHelper.GetSingle(string.Format("select containerstepdispatchid from containerstepdispatch where containerid='{0}' and workflowstepid='{1}'", para["ContainerID"], para["WorkflowStepID"])).ToString();
                var faReportID = Guid.NewGuid().ToString();
                if (faDispatcID != null)
                {
                    //工序级有派工，才自动报工
                    sqlList.Add(string.Format(@"insert into containerstepworkreport csw (csw.containerstepdispatchid,csw.checktype,csw.containerid,csw.workflowstepid,csw.createdate,csw.factoryid,
                            csw.isuse,csw.qty,csw.resourceid,csw.teamid,csw.workcenterid,csw.workerid,csw.lossqty,csw.containerstepworkreportid) 
                            values ('{0}','{1}','{2}','{3}',to_date('{4}','yyyy-mm-dd hh24:mi:ss'),'{5}','{6}',{7},'{8}','{9}','{10}','{11}',{12},'{13}')",
                               faDispatcID.ToString(), "2", para["ContainerID"], para["WorkflowStepID"], para["CreateDate"], para["FactoryID"], para["Isuse"], para["Qty"], para["ResourceID"], para["TeamID"], para["WorkcenterID"], para["WorkerID"], para["Lossqty"], faReportID));
                    //批次检验记录表
                    sqlList.Add(string.Format(@"insert into containercheckinfo(containerid,factoryid,workflowstepid,checkerid,checkqty,acceptanceqty,lossqty,reworkqty,defectqty,
                    containercheckinfoid,createdate,checknote,firstcheckbillno,containerstepworkreportid,isuse,istransfer,checktypenote,firstcheckcontainerno,acceptanceqty2)
                    values('{0}','{1}','{2}','{3}',{4},{5},{6},{7},{8},'{9}',to_date('{10}','yyyy-mm-dd hh24:mi:ss'),'{11}','{12}','{13}',0,0,'{14}','{15}',{16})",
                            para["ContainerID"], para["FactoryID"], para["WorkflowStepID"], checkerid, para["Qty"], orderReport.PassQty, orderReport.LossQty, 0, 0,
                             Guid.NewGuid().ToString(), orderReport.ReportDate, "", "", faReportID, "", "", para["Qty"]));
                }

                //检测项信息
                string CheckMsg = string.Empty;
                foreach (var checkItem in orderReport.CheckItems)
                {
                    DataTable checkItemDt = OracleHelper.Query(string.Format(@"select st.* from stepcheckpoint st where st.workflowstepid='{0}' and st.stepcheckpointid='{1}'", dispatchDt.Rows[0]["WorkflowStepID"].ToString(), checkItem.StepCheckPointID)).Tables[0];
                    if (checkItemDt.Rows.Count == 0)
                    {
                        CheckMsg += "MES中未找到此检测项,对应字段：CheckItemID" + checkItem.StepCheckPointID;
                        continue;
                    }
                    GetSaveCheckResultSql(dispatchDt.Rows[0], checkItem.StepCheckPointID, null, reportID, para["WorkerID"], checkerid, para["CreateDate"], checkItem.CheckResult, ref sqlList);
                }

                if (!string.IsNullOrWhiteSpace(CheckMsg))
                {
                    msg = CheckMsg;
                    return msg;
                }

                if (sqlList.Count > 0)
                {
                    OracleHelper.ExecuteSqlTran(sqlList);//报工、检测结果录入
                    msg = "操作成功";
                }

            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }

        void GetSaveCheckResultSql(DataRow dispatchItem, string checkItemId, DataTable childConDt, string reportID, string employeeid, object checkempid, string createDate, string result, ref ArrayList sqlList)
        {
            DataTable existDt = OracleHelper.Query(string.Format(@"select * from stepcheckpointresult sr where sr.containerid='{0}'  and sr.stepcheckpointid='{1}'",
                dispatchItem["containerid"].ToString(), checkItemId)).Tables[0];

            string updateSql = @"update STEPCHECKPOINTRESULT sr set sr.workerid='{0}',sr.workcheckpointresultnote='{1}',sr.workcheckpointresultnotedis='{2}',
                        sr.createdate=to_date('{3}','yyyy/mm/dd hh24:mi:ss'),sr.tempdealfail=0,lastchangedate=sysdate,checkerid='{4}',checkpointresultnote='{5}',checkpointresultnotedis='{6}' where sr.stepcheckpointresultid='{7}'";

            string insertSql = @"insert into stepcheckpointresult (lastchangedate,workerid,workcheckpointresultnote,workcheckpointresultnotedis,containerid,childcontainerid,createdate,factoryid,stepcheckpointid,
                        stepcheckpointresultid,containerstepworkreportid,checkerid,checkpointresultnote,checkpointresultnotedis) values (sysdate,'{0}','{1}','{2}','{3}','{4}',to_date('{5}','yyyy/mm/dd hh24:mi:ss'),'{6}','{7}','{8}','{9}','{10}','{11}','{12}')";

            if (existDt.Rows.Count > 0)
            {
                sqlList.Add(string.Format(updateSql, employeeid, result, result, createDate, checkempid, result, result, existDt.Rows[0]["stepcheckpointresultid"].ToString()));
            }
            else
            {
                sqlList.Add(string.Format(insertSql, employeeid, result, result, dispatchItem["containerid"].ToString(), "", createDate, dispatchItem["FACTORYID"].ToString(), checkItemId, Guid.NewGuid().ToString(), reportID, checkempid, result, result));
            }

        }
        #endregion

        #region "实体类对象"
        public class SpecStatus
        {
            public string MfgOrderName { set; get; }// 订单号",
            public string ContainerName { set; get; } //批次号",
            public string Description { set; get; } //零件名称",
            public string SpecNO { set; get; } //工序序号",
            public string ContainerStepDispatchID { set; get; } //派工id",
            public string OPDesc { set; get; }//工序名称",
            public string State { set; get; }//工序状态"
        }

        public class OrderReport
        {
            public string DispatchID { set; get; }//MES派工标识
            public string MfgOrderName { set; get; }//生产订单号
            public string ProductName { set; get; }//件号
            public string Description { set; get; }//件号名称
            public string ContainerName { set; get; }//批次号
            public string Process_no { set; get; }//工艺规程编号
            public string SpecNo { set; get; }//工序号
            public string OPDesc { set; get; }//工序名称
            public string PassQty { set; get; }//合格数量
            public string LossQty { set; get; }//报废数量
            public string ReportDate { set; get; }//完工时间
            public string ReportResDesc { set; get; }//设备名称
            public string ReportResName { set; get; }//设备编码
            public string ReportEmpFullName { set; get; }//操作者名字
            public string ReportEmpName { set; get; }//操作者员工号
            public string CheckFullName { set; get; }//检验者名字
            public string CheckEmpName { set; get; }//检验者员工号
            public List<CheckItem> CheckItems { set; get; }//检测项结果集
        }

        public class CheckItem
        {
            public string StepCheckPointID { set; get; }//MES检测项标识
            public string CheckNo { set; get; }//顺序号
            public string CheckResult { set; get; }//实际值
        }
        #endregion
    }
}
